package com.mapaower.admin.exception;

import com.mapaower.admin.utils.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseResult<?>> handleGlobalException(Exception ex, WebRequest request) {
        logger.error("发生未处理的异常: {}", ex.getMessage(), ex);
        return new ResponseEntity<>(
                ResponseResult.error("服务器内部错误，请稍后再试"),
                HttpStatus.INTERNAL_SERVER_ERROR
        );
    }

    /**
     * 处理认证相关异常
     */
    @ExceptionHandler(BadCredentialsException.class)
    public ResponseEntity<ResponseResult<?>> handleBadCredentialsException(BadCredentialsException ex) {
        logger.error("认证失败: {}", ex.getMessage());
        return new ResponseEntity<>(
                ResponseResult.error("用户名或密码错误"),
                HttpStatus.UNAUTHORIZED
        );
    }

    /**
     * 处理禁用账户异常
     */
    @ExceptionHandler(DisabledException.class)
    public ResponseEntity<ResponseResult<?>> handleDisabledException(DisabledException ex) {
        logger.error("账户已禁用: {}", ex.getMessage());
        return new ResponseEntity<>(
                ResponseResult.error("账户已被禁用，请联系管理员"),
                HttpStatus.UNAUTHORIZED
        );
    }

    /**
     * 处理锁定账户异常
     */
    @ExceptionHandler(LockedException.class)
    public ResponseEntity<ResponseResult<?>> handleLockedException(LockedException ex) {
        logger.error("账户已锁定: {}", ex.getMessage());
        return new ResponseEntity<>(
                ResponseResult.error("账户已被锁定，请联系管理员"),
                HttpStatus.UNAUTHORIZED
        );
    }

    /**
     * 处理访问拒绝异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<ResponseResult<?>> handleAccessDeniedException(AccessDeniedException ex) {
        logger.error("访问被拒绝: {}", ex.getMessage());
        return new ResponseEntity<>(
                ResponseResult.error("没有权限访问此资源"),
                HttpStatus.FORBIDDEN
        );
    }

    /**
     * 处理请求参数验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResponseResult<?>> handleValidationException(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> 
                errors.put(error.getField(), error.getDefaultMessage())
        );
        logger.error("请求参数验证失败: {}", errors);
        return new ResponseEntity<>(
                ResponseResult.error("请求参数验证失败", errors),
                HttpStatus.BAD_REQUEST
        );
    }

    /**
     * 处理资源未找到异常
     */
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ResponseResult<?>> handleResourceNotFoundException(ResourceNotFoundException ex) {
        logger.error("资源未找到: {}", ex.getMessage());
        return new ResponseEntity<>(
                ResponseResult.error(ex.getMessage()),
                HttpStatus.NOT_FOUND
        );
    }

    /**
     * 处理业务逻辑异常
     */
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ResponseResult<?>> handleBusinessException(BusinessException ex) {
        logger.error("业务逻辑异常: {}", ex.getMessage());
        return new ResponseEntity<>(
                ResponseResult.error(ex.getMessage()),
                HttpStatus.BAD_REQUEST
        );
    }
}